import React, { useState,useEffect } from 'react';
import { ConnectProps, history } from 'umi';
import { Helmet } from 'react-helmet';

import { Topic } from '@/components';
import { queryQuestionRecord,
  questionDetail,
  alongAnswer,
  queryExamRecord,
  getAnswerRecordDetail,
  getAnswerExamRecordDetail,
  getWrongBook } from '@/services/edu'
import  styles from './index.less';
import { Toast } from 'antd-mobile';
const unique =(arr,key)=>{
  var result = [];
    var obj = {};
    for(var i =0; i<arr.length; i++){
       if(!obj[arr[i][key]]){
          result.push(arr[i]);
         obj[arr[i].key] = true;
       }
    }
    return result
}
function Answer() {
  const { query = {} } = history.location as any;
  const { id,itemOrder,chapterId,sectionId } = query;
  // 题目详情
  const [topicInfo,settopicInfo] = useState<any>({})
  // 当前页数
  const [curPage,setcurPage] =useState(1)
  // 总数
  const [total,setTotal] =useState(0)
  // 题目ids列表
  const [topicList,settopicList] = useState<any>([])
  //1练习 2模拟  3考试
  const [type,setType] =useState<1|2>(2)
  // 正确的数量
  const [correctNumber,setcorrectNumber] =useState(0)
  // 错误的数量
  const [failNumber,setfailNumber] =useState(0)
  // 错误列表
  const [failList,setfailList] =useState([])
  // 已答题列表
  const [answerItems,setanswerItems] = useState([])
  // 答题
  const [answer,setanswer] =useState([])
  // 分数
  const [fraction,setfraction] =useState(0)
  // 设置
  const [projectSetting,setprojectSetting] =useState<any>({})
  // 是否查看

  // 是否正确
  const [isRight,setisRight] = useState(false)
  // 是否考试
  const [isExam] = useState(query.isExam==='1')
  // 是否错题本
  const [isError] = useState(query.isError==='1')
  
  
  const init =async()=>{
    let res:any ={}
    if(isExam){
      res = await getAnswerExamRecordDetail({recordId:id,pageSize:1000})
    }else if(isError){
      
      const payload:any = {
        pageIndex:1,
        pageSize:1000,
        type:Number(query.type)
      };
      if(chapterId){
        payload.chapterId=chapterId
      }else{
        payload.sectionId=sectionId
      }
      res = await getWrongBook(payload)
    }else{
      res = await getAnswerRecordDetail({recordId:id,pageSize:1000})
    }
      // const xx= await queryExamRecord({recordId:id})
      // debugger
      const {
        list=[],
        total,
      } = res.response||{}
      const recordOrder =Number(itemOrder||'0')
      if(list.length){
        const correctList =list.filter(item=>item.doRight)
        setcorrectNumber(correctList.length)
        setfailNumber(total-correctList.length)
        setcurPage(recordOrder+1)
        setTotal(total)
        settopicList(list)
        
        setTopInfo(recordOrder+1,list)
        // fetchquestionDetail(questionList[recordOrder])
      }
    
    // else{
    //   const res = await queryQuestionRecord({recordId:id})
    //   if(res?.code===1&&res?.response){
    //     const {
    //       questionIds='',
    //       recordOrder=0,
    //       questionCorrect=0,
    //       questionError=0,
    //       recordSum,
    //       status
    //     } = res.response||{}
    //     const questionList =questionIds.split(',')
    //     debugger
    //     if(questionList.length){
    //       setcorrectNumber(questionCorrect)
    //       setfailNumber(questionError)
    //       setcurPage(recordOrder+1)
    //       setTotal(recordSum)
    //       settopicList(questionList)
    //       fetchquestionDetail(questionList[recordOrder])
    //     }
        
    //   }
    // }
     

    
    
    
  }
  const fetchquestionDetail = async(questionId,list?)=>{
    if(!questionId) return
    const res = await questionDetail({questionId,recordId:id})
    if(res?.code===1 && res.response){
      const {
        name,
        titleItems=[]
      } = res.response
      
      settopicInfo(res.response)
      
    }
  }
  const setTopInfo =(cur?,list?)=>{
    list = list||topicList
    const info =list[cur-1];
    settopicInfo(info)
    if(isExam){
      settopicInfo(info)
    }else{
      // fetchquestionDetail(info)
    }
    
    setcurPage(cur)
    setanswer(info?.userCorrect||[])
    setisRight(info?.doRight||false)
    
  }

  useEffect(()=>{
    init()
  },[])
  // 遍历选项
  const renderOptions = (arr=[]) => {
    
    
    return arr.map(item=>{
      return {
        label: <div dangerouslySetInnerHTML= {{ __html: item.content }}></div>, 
        value: item.prefix
      }
    })
  }
  const renderQuestion = (data:any={})=> {
    return data?<div dangerouslySetInnerHTML= {{ __html: data }}></div>:''
  }
  const onPre = async(page?)=>{
    if(curPage>1){
      setTopInfo(curPage-1)
    }
  }
  // 下一题
  const onNext = async () => {
    
    if(topicList.length>curPage){
      setTopInfo(curPage+1)
    }else{
      history.goBack()
    }
  }
  const handleChange = (value)=>{
    const {
      correct,
      questionType
    } =topicInfo
    const isRight = correct.split(',').sort().toString()===value.sort().toString()
    setisRight(isRight)
    return isRight
  }
  // 提交答案
  const onSubmit = async(value=[],alist=[]) => {
    // 是否正确
    const doRight = handleChange(value)

    const res = await alongAnswer({
      correct:value.toString(),
      questionId:topicInfo.id,
      recordId:id,
      doRight,
      isLast:topicList.length === curPage
    })
    
    if(topicList.length === curPage){
      return history.push(`/exam/score?id=${id}`)
    }
    if(topicList.length>curPage){
      setTopInfo(curPage+1)
    }
    
    // setanswerItems([...answerItems,])
    
  }

  return (
    <div className={styles.answer}>
      <Helmet title={projectSetting?.name}/>
      
      {topicInfo.shortTitle&&<div key={topicInfo.id}>
        <Topic 
        question={renderQuestion(topicInfo.shortTitle)}
        title={projectSetting?.name}
        current={curPage}
        isCheckbox={topicInfo.questionType===2}
        total={total}
        timeLimit={projectSetting?.suggestTime}
        isOnlyShow={!isError}
        isRight={isRight}
        id={topicInfo.id}
        value={isError?'':topicInfo.userCorrect}
        isError={isError}
        // 正确答案
        answer={topicInfo.correct?.split(',')}
        correctNumber={correctNumber}
        onPre={() => onPre()}
        onNext={() => onNext()}
        failNumber={failNumber}
        onChange={(v)=>handleChange(v)}
        onSubmit={(v)=>onSubmit(v,answerItems)}
        type={type}
        topicInfo={topicInfo}
        parse={renderQuestion(topicInfo.analyze)}
        options={renderOptions(topicInfo.items)}
        forceEnd={(v)=>onSubmit(v,answerItems)} />
      </div>}
    </div>
  );
}

export default Answer;
